# -*- coding: utf-8 -*-
###############################################################################
# file    : my_pycurl.py
# author  : wangyubin
# date    : Thu Apr  3 14:48:42 2014
# 
# brief   : upload or download use libcurl and pycurl
#           安装 pycurl之前需要安装 sudo apt-get install libcurl3-dev
# history : init
###############################################################################

import pycurl
import os
import StringIO
import json
import urllib

def progress(download_t, download_d, upload_t, upload_d):
    """ process sample
    """

    #print "Total to download", download_t
    #print "Total downloaded", download_d
    #print "Total to upload", upload_t
    #print "Total uploaded", upload_d
    pass


def set_opt(c, url):
    """ 设置请求参数
    """

    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.MAXREDIRS, 5)
    c.setopt(pycurl.CONNECTTIMEOUT, 60)
    c.setopt(pycurl.TIMEOUT, 300)
    c.setopt(pycurl.POST, 1)

    c.setopt(pycurl.URL, url)  #设置要访问的网址
        

def upload_file(url, files, dic_data={}, progress_func=progress):
    """ upload file by http use pycurl
    可以传输一个或者多个文件

    @param: files 格式  [('xxx', filepath), ('xxx', filepath)......]
    """
    
    c = pycurl.Curl()
    fp = StringIO.StringIO()
    c.setopt(pycurl.WRITEFUNCTION, fp.write)
    set_opt(c, url)
    c.setopt(pycurl.NOPROGRESS, 0)
    c.setopt(pycurl.PROGRESSFUNCTION, progress_func)
    l = []
    # 上传的文件
    for (k, v) in files:
        l.append((k, (c.FORM_FILE, v.encode('utf-8')))) # 文件名中文

    # http 参数
    for (k, v) in dic_data.iteritems():
        l.append((k, (c.FORM_CONTENTS, v.encode('utf-8'))))

    print l
    c.setopt(c.HTTPPOST, l)
    try:
        c.perform()                 # 执行 http 请求
    except:
        return (False, None)
    
    if c.getinfo(pycurl.RESPONSE_CODE) == 200:
        dic_json = json.loads(fp.getvalue())
        return (True, dic_json)
    else:
        return (False, None)


def post_request(url, dic={}):
    """ post请求
    """
    
    c = pycurl.Curl()
    fp = StringIO.StringIO()
    c.setopt(pycurl.WRITEFUNCTION, fp.write)
    set_opt(c, url)
    c.setopt(pycurl.POSTFIELDS, urllib.urlencode(dic))
    try:
        c.perform()                 # 执行 http 请求
    except:
        return (False, None)
    
    if c.getinfo(pycurl.RESPONSE_CODE) == 200:
        dic_json = json.loads(fp.getvalue())
        return (True, dic_json)
    else:
        return (False, None)
    




